package com.chuanjiabao.wisdom.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;

import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.adapter.ApplicationState;
import com.chuanjiabao.wisdom.adapter.BaseFragmentAdapter;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.FamilyTextCallbackBean;
import com.chuanjiabao.wisdom.bean.STSCallBackBean;
import com.chuanjiabao.wisdom.databinding.ActivityFindToSeeBinding;
import com.chuanjiabao.wisdom.ui.BaseActivity;
import com.chuanjiabao.wisdom.ui.fragment.FindToSeeFragment;
import com.chuanjiabao.wisdom.util.BHThreadPool;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.SpUtils;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.lzy.okgo.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * <p>
 * 图片查看界面
 * 1 图片可以放大缩小
 * 2 视频播放
 * 3 文本查看
 * 4 标题显示当前位置
 */
public class FindToSeeActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    ActivityFindToSeeBinding binding;

    List<Fragment> list = new ArrayList<>();
    ApplicationState applicationState = new ApplicationState();

    int position = 0;
    List<FamilyTextCallbackBean.DataBeanX.DataBean> listBeans;

    BaseFragmentAdapter<Fragment> fragmentAdapter;

    OSSClient oss;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_find_to_see);
        binding.setActivity(this);
        initView();
    }

    private void initView() {
        setBack();
        getSTS();
        try {
            position = getIntent().getIntExtra("module_position", 0);
            listBeans = (List<FamilyTextCallbackBean.DataBeanX.DataBean>) getIntent().getSerializableExtra("module_list_bean");
            fragmentAdapter = new BaseFragmentAdapter<>(getSupportFragmentManager());
        } catch (Exception e) {
            LogUtil.e("intent 传递出错");
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (applicationState.isMainSliding() && position == 1) {
            applicationState.setMainSliding(false);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (!applicationState.isMainSliding() && state != ViewPager.SCROLL_STATE_IDLE) {
            applicationState.setMainSliding(true);
        }
    }

    public void getSTS() {
        HTTPAPI.getInstance().getSTS(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("获取STS成功" + s);
                if (!StringUtil.isFail(s)) {
                    SpUtils.clear(FindToSeeActivity.this);
                    startActivity(new Intent(FindToSeeActivity.this, LoginActivity.class));
                    ToastUtil.showToast("登陆过期，请重新登陆");
                    return;
                } else {
                    final STSCallBackBean bean = GsonUtil.GsonToBean(s, STSCallBackBean.class);
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(
                                    bean.getData().getAccessKeyId(),
                                    bean.getData().getAccessKeySecret(),
                                    bean.getData().getSecurityToken()) {
                                @Override
                                public OSSFederationToken getFederationToken() {
                                    return super.getFederationToken();
                                }
                            };
                            OSSLog.enableLog();
                            oss = new OSSClient(FindToSeeActivity.this, "https://" + bean.getData().getEndPoint(),
                                    credentialProvider, FApplication.getInstance().getClientConfiguration());
                            handler.sendEmptyMessage(200);
                        }
                    };
                    BHThreadPool.getInstance().executeTask(runnable);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("获取STS" + e.getMessage());
            }
        });
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                for (FamilyTextCallbackBean.DataBeanX.DataBean dataBean : listBeans) {
                    list.add(new FindToSeeFragment(oss, dataBean));
                }
                fragmentAdapter.addData(list);
                binding.vpModule.setAdapter(fragmentAdapter);
                binding.vpModule.setCurrentItem(position);
                binding.vpModule.addOnPageChangeListener(FindToSeeActivity.this);
            } catch (Exception e) {
                LogUtil.e("fragment添加出错");
            }
        }
    };


}
